#coding=utf-8

import logging
import htmllib
import urllib
import sys
import datetime
import re


def get_display_date(then, now=None):
    def agohence(n, what, divisor=None):
        if divisor: n = n // divisor
        out = str(abs(n)) + '' + what       # '2 day'
        out += ''                           # '2 days '
        if n < 0:
            out += '以后'
        else:
            out += '以前'
        return out                           # '2 days ago'
    oneday = 24 * 60 * 60

    if not now: now = datetime.datetime.utcnow()
    if type(now).__name__ == "DateTime":
        now = datetime.datetime.fromtimestamp(now)
    if type(then).__name__ == "DateTime":
        then = datetime.datetime.fromtimestamp(then)
    elif type(then).__name__ == "date":
        then = datetime.datetime(then.year, then.month, then.day)
    delta = now - then
    deltaseconds = int(delta.days * oneday + delta.seconds + delta.microseconds * 1e-06)
    deltadays = abs(deltaseconds) // oneday
    if deltaseconds < 0: deltadays *= -1 # fix for oddity of floor

    if deltadays:
        if abs(deltadays) < 4:
            return agohence(deltadays, '天')

        out = then.strftime('%m月%d日') # e.g. 'June 13'
        month = then.month
        day = then.day
        if then.year != now.year or deltadays < 0:
            out = '%s年' + out % then.year
        if out[0] == '0':
            out = out[1:]
        return out

    if int(deltaseconds):
        if abs(deltaseconds) > (60 * 60):
            return agohence(deltaseconds, '小时', 60 * 60)
        elif abs(deltaseconds) > 60:
            return agohence(deltaseconds, '分', 60)
        else:
            return agohence(deltaseconds, '秒')

    deltamicroseconds = delta.microseconds
    if delta.days: deltamicroseconds = int(delta.microseconds - 1e6) # datetime oddity
    if abs(deltamicroseconds) > 1000:
        return agohence(deltamicroseconds, '微秒', 1000)

    return agohence(deltamicroseconds, '微秒')
